package com.liangtian.mdm.material.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.authentication.JWTUtil;
import com.liangtian.mdm.base.constants.ResultCode;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.response.BaseResponse;
import com.liangtian.mdm.dm.jsp.common.ExcelUtil;
import com.liangtian.mdm.material.common.util.ExcelExportUtil;
import com.liangtian.mdm.material.dao.WlbmJldwDao;
import com.liangtian.mdm.material.model.WlbmJldw;
import com.liangtian.mdm.material.service.WlbmJldwService;
import com.liangtian.mdm.util.ExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@SuppressWarnings({"unchecked", "rawtypes"})
@Service
@Slf4j
public class WlbmJldwServiceImpl implements WlbmJldwService {

    @Autowired
    private WlbmJldwDao wlbmJldwDao;

    @Autowired
    JdbcDao jdbcDao;

    @Transactional
    @Override
    public PageInfo getWlbmJldwListByCond(Map<String, Object> map) {
        PageInfo<List<WlbmJldw>> pageInfo = null;
        try {
            Object pNo = map.get("pageNum");
            int pageNum;
            int pageSize;
            // 页码
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页,模型定义页面要显示数据条数 例如 10,20,50,100
            pageSize = Integer.parseInt(map.get("limit").toString());
            // 开始分页标志（当前页，显示条数）
            PageHelper.startPage(pageNum, pageSize);
            List<WlbmJldw> wlbmJldwMapList = wlbmJldwDao.getWlbmJldwListByCond(map);
            pageInfo = new PageInfo(wlbmJldwMapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public int insertWlbmJldw(WlbmJldw wlbmJldw) {
        return wlbmJldwDao.insertWlbmJldw(wlbmJldw);
    }

    @Override
    public void updateWlbmJldw(WlbmJldw wlbmJldw) {
        wlbmJldwDao.updateWlbmJldw(wlbmJldw);
    }

    @Override
    public int checkWlbmJldwExist(WlbmJldw wlbmJldw) {
        Map<String, Object> map = new HashMap<>();
        map.put("jldw", wlbmJldw.getJldw());
        map.put("jldwId", wlbmJldw.getJldwId());
        return wlbmJldwDao.checkWlbmJldwExist(map);
    }

    @Override
    public WlbmJldw getWlbmJldwByIdOrName(WlbmJldw wlbmJldw) {
        return wlbmJldwDao.getWlbmJldwByIdOrName(wlbmJldw);
    }

    @Override
    public int deleteWlbmJldwByIds(Map<String, Object> map) {
        return wlbmJldwDao.deleteWlbmJldwByIds(map);
    }

    @Override
    public void updateWlbmJldwStatus(WlbmJldw wlbmJldw) {
        wlbmJldwDao.updateWlbmJldwStatus(wlbmJldw);
    }

    @Override
    public List<WlbmJldw> queryWlbmJldws() {
        return wlbmJldwDao.queryWlbmJldws();
    }

    /**
     * 校验用户输入的数据，并插入数据库
     */
    @Override
    public BaseResponse checkImportListThenInsert(List<Object[]> valueList, String tableName) throws IOException {
        String fileName = "";
        BaseResponse baseResponse = new BaseResponse().ok();
        StringBuilder sb = new StringBuilder();
        valueList.remove(0);
        boolean importedDataHasExist = true;
        if (CollectionUtils.isNotEmpty(valueList)) {
            //获取用户将导入的数据n条
            for (int j = 0; j < valueList.size(); j++) {
                //获取行
                String[] row = (String[]) valueList.get(j);
                for (int k = 0; k < row.length; k++) {
                    //获取每固定行一列（0,0）
                    String cell = row[k];
                    sb.append(checkColumn(j, k, cell));
                }
            }
        } else {
            sb.append("@@@@" + "请在模板中填写需要导入的数据！");
            importedDataHasExist = false;
        }

        if ("".equals(sb.toString())) {
            String[] headArray = {"USER_NAME", "USER_ACCOUNT", "USER_EMAIL", "USER_PHONE", "USER_TELEPHONE", "ORGANIZATION_ID"};
            List<String> sqls = genInsertJldwSql(tableName, valueList, headArray);
            boolean success = jdbcDao.executeSqlList(sqls, true);
            if (success) {
                baseResponse = BaseResponse.genResponse(ResultCode.SUCCESS.getCode(), "导入成功!");
            }
        } else {
            fileName = "wlbmJldwImportError" + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
            ExportUtil.errTxt(sb.toString(), fileName);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("errorFileName", fileName);
            if (importedDataHasExist){
                baseResponse = BaseResponse.genResponse(ResultCode.IMPORTED_DATA_HAS_EXIST, jsonObject);
            }else {
                baseResponse = BaseResponse.genResponse(ResultCode.IMPORTED_FILE_IS_EMPTY, jsonObject);
            }
        }
        return baseResponse;
    }

    /**
     * 校验导入的数据完整性和与库中数据是否冲突
     */
    private String checkColumn(int row, int column, String cell) {
        StringBuilder sb = new StringBuilder();
        //校验每行数据的每一列，错误的拼接成string，正确的不拼接
        //说明是第一列（校验计量单位）
        if (column == 0) {
            if (StringUtils.isBlank(cell)) {
                sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,计量单位不可为空！");
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("jldw", cell);
                int count = wlbmJldwDao.checkWlbmJldwExist(map);
                if (count > 0) {
                    sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,计量单位").append("'").append(cell).append("'").append("已存在！");
                }
            }

        } else if (column == 1) {//说明是第二列（校验单位符号）
            if (StringUtils.isBlank(cell)) {
                sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,单位符号不可为空！");
            }
        } else if (column == 2) {//说明是第三列（校验性质）
            if (StringUtils.isBlank(cell)) {
                sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,性质不可为空！");
            }
        } else if (column == 3) {//说明是第三列（校验系数）
            if (StringUtils.isNotEmpty(cell.trim())) {
                if (Integer.parseInt(cell) > 10000 || Integer.parseInt(cell) < 0) {
                    sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,系数只能填写大于0小于10000的数字！");
                }
            }
        } else if (column == 4) {//说明是第三列（校验是否准确）
            if (StringUtils.isBlank(cell)) {
                sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,是否准确不可为空！");
            } else {
                if ("1".equals(cell) || "0".equals(cell) || "是".equals(cell) || "否".equals(cell)) {

                } else {
                    sb.append("@@导入数据第").append(row + 2).append("行,第").append(column + 1).append("列,是否准确输入错误!");
                }
            }
        }
        return sb.toString();
    }

    @Override
    public List<String> genInsertJldwSql(String tableName, List<Object[]> subList, String[] headArray) {
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String userAccount = JWTUtil.getUsername(token);

        List<String> sqls = new ArrayList<>();
        // 获取值集合
        for (int j = 0; j < subList.size(); j++) {
            StringBuilder sb = new StringBuilder("");
            sb.append(" insert into ").append(tableName).append(" (")
                    .append("JLDW,FH,XZ,XS,ZQ,XH,CREATER,CREATETIME,STATUS")
                    .append(")")
                    .append(" VALUES(");

            String[] row = (String[]) subList.get(j);
            //拼接sql值
            sb.append("'").append(row[0]).append("',")
                    .append("'").append(row[1]).append("',")
                    .append("'").append(row[2]).append("',");
            if ("".equals(row[3]) || " ".equals(row[3])) {
                sb.append("'0',");
            } else {
                sb.append(Integer.parseInt(row[3])).append(",");
            }
            if ("0".equals(row[4]) || "1".equals(row[4])) {
                sb.append("'").append(row[4]).append("',");
            } else if ("是".equals(row[4])) {
                sb.append("'1',");
            } else if ("否".equals(row[4])) {
                sb.append("'0',");
            }
            sb.append("'0', '").append(userAccount).append("', ").append("sysdate(),").append("'1' )");
            sqls.add(sb.toString());
            log.info(sb.toString());
        }
        return sqls;
    }

    @Override
    public void exportWlbmJldw(List<WlbmJldw> list, HttpServletResponse response) {
        try {
            String tablename = "物料计量单位";
            // 声明一个工作薄
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("物料计量单位");
            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = null;
            CellStyle style = ExcelUtil.createCellTextStyle(workbook);
            cell = row.createCell(0);
            sheet.setDefaultColumnStyle(0, style);
            cell.setCellValue("单位符号");
            cell = row.createCell(1);
            sheet.setDefaultColumnStyle(1, style);
            cell.setCellValue("计量单位");
            cell = row.createCell(2);
            sheet.setDefaultColumnStyle(2, style);
            cell.setCellValue("性质");
            cell = row.createCell(3);
            sheet.setDefaultColumnStyle(3, style);
            cell.setCellValue("状态");
            cell = row.createCell(4);
            sheet.setDefaultColumnStyle(4, style);
            cell.setCellValue("是否准确");
            cell = row.createCell(5);
            sheet.setDefaultColumnStyle(5, style);
            cell.setCellValue("系数");
            for (int i = 0; i < list.size(); i++) {
                WlbmJldw getWlLb = list.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(getWlLb.getFh());
                cell = row.createCell(1);
                cell.setCellValue(getWlLb.getJldw());
                cell = row.createCell(2);
                cell.setCellValue(getWlLb.getXz());
                cell = row.createCell(3);
                cell.setCellValue(getWlLb.getStatus().equals("1") ? "活动" : "冻结");
                cell = row.createCell(4);
                cell.setCellValue(getWlLb.getZq().equals("1") ? "是" : "否");
                cell = row.createCell(5);
                String xishu = String.valueOf(getWlLb.getXs());
                cell.setCellValue(xishu);
                if ("null".equals(xishu)) {
                    cell.setCellValue("");
                }
            }
            ExcelExportUtil.outExportExcel(tablename, workbook, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public PageInfo getWlbmJldwListByCond2(Map<String, Object> map) {
        PageInfo<List<WlbmJldw>> pageInfo = null;
        try {
            Object pNo = map.get("pageNum");
            int pageNum, pageSize;
            // export
            if (pNo != null && !"NaN".equals(pNo)) {
                pageNum = Integer.parseInt(pNo.toString());// 页码
            } else {
                pageNum = 1;
            }
            // pageSize=0时不分页
            pageSize = Integer.parseInt(map.get("pageSize").toString());// 模型定义页面要显示数据条数
            // 例如
            // 10,20,50,100
            PageHelper.startPage(pageNum, pageSize);// 开始分页标志（当前页，显示条数）
            List<WlbmJldw> wlbmJldwMapList = wlbmJldwDao.getWlbmJldwListByCond(map);
            pageInfo = new PageInfo(wlbmJldwMapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }


}
